package cn.dqy.gotanserver.handle;

import cn.dqy.gotanserver.config.ConfigClass;
import cn.dqy.gotanserver.dto.ChannelInfo;
import cn.dqy.gotanserver.support.EmailSupport;
import cn.dqy.gotanserver.support.SmsSupport;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.locks.LockSupport;

public class AuthInboundHandle extends ChannelInboundHandlerAdapter {
    static Logger logger = LoggerFactory.getLogger(AuthInboundHandle.class);

    ConfigClass configClass;
    EmailSupport emailSupport;
    SmsSupport smsSupport;
    Map<String, ChannelInfo> channelInfoMap;

    public AuthInboundHandle(ConfigClass configClass,EmailSupport emailSupport,SmsSupport smsSupport,Map<String,ChannelInfo> channelInfoMap){
        this.configClass=configClass;
        this.emailSupport=emailSupport;
        this.smsSupport=smsSupport;
        this.channelInfoMap=channelInfoMap;
    }

    //简单认证，客户端连接后必须发一个双方约定的口令
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        int authPassword = configClass.getAuthPassword().intValue();
        ByteBuf byteBuf= (ByteBuf) msg;
        int authInt = byteBuf.readInt();
        logger.info("auth int = {}",authInt);
        byteBuf.release();

        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        String hostName = channel.remoteAddress().getHostName() + ":" + channel.remoteAddress().getPort();

        if(authInt!=authPassword){
            logger.info("权限验证失败，{} 是非法连接，断开!",hostName);
            ctx.channel().close();
        }else {
            logger.info("权限校验成功.新的客户端连接");

            //对于正确来源的连接，发送邮件或短信通知
            if(configClass.isSendEmail()) emailSupport.sendSimpleMail("新的连接到来"+hostName);
            smsSupport.addSmsContent(hostName);

            ctx.pipeline().remove(this); //通过，下次不走该处理器
            ctx.fireChannelActive();

            //为该链接建立存储目录
            String addrKey = channel.remoteAddress().getHostName() + ":" + channel.remoteAddress().getPort(); //机器唯一标识
            String pullStreamFileDic=configClass.getFileRootPath()+addrKey.replaceAll(":","")+"/"; //推流文件存储目录
            logger.info("推流文件存储目录 = {}",pullStreamFileDic);
            FileUtils.deleteDirectory(new File(pullStreamFileDic));
            FileUtils.forceMkdir(new File(pullStreamFileDic));

            channelInfoMap.get(addrKey).setPullStreamPath(pullStreamFileDic);
            logger.info("推流文件目录创建完成");
        }
    }
}
